package com.xdl.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xdl.common.constants.CommonConstants;
import com.xdl.common.exception.BelugaException;
import com.xdl.common.response.ResponseCollection;
import com.xdl.common.response.ResponseResult;
import com.xdl.common.utils.StringUtils;
import com.xdl.modules.system.entity.SysPermission;
import com.xdl.modules.system.entity.SysRole;
import com.xdl.modules.system.model.RoleModel;
import com.xdl.modules.system.model.TreeModel;
import com.xdl.modules.system.service.SysPermissionService;
import com.xdl.modules.system.service.SysRoleService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author iron guo
 * @since 2022-03-08
 */
@Slf4j
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysPermissionService permissionService;

    @GetMapping("queryall")
    public ResponseCollection<SysRole> queryall() {
        List<SysRole> list = sysRoleService.list();
        if (list == null || list.size() <= 0) {
            BelugaException.fatal("未找到角色信息");
        }
        return ResponseCollection.Success(list);
    }

    /**
     * 编辑
     *
     * @param role
     * @return
     */
    @PostMapping("/edit")
    public ResponseResult<Boolean> edit(@RequestBody SysRole role) {
        SysRole sysrole = sysRoleService.getById(role.getId());
        if (sysrole == null) {
            return ResponseResult.Error("未找到对应实体");
        } else {
            role.setUpdateTime(LocalDateTime.now());
            boolean ok = sysRoleService.updateById(role);
            return ResponseResult.Success(ok);
        }
    }


    /**
     * 添加
     *
     * @param role
     * @return
     */
    @PostMapping("/add")
    public ResponseResult<Boolean> add(@RequestBody SysRole role) {
        role.setCreateTime(LocalDateTime.now());
        return ResponseResult.Success(sysRoleService.save(role));
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public ResponseResult<?> delete(@RequestParam(name = "id", required = true) String id) {
        boolean delete = sysRoleService.deleteRole(id);
        return ResponseResult.Success("删除成功！");
    }

    /**
     * 分页列表查询
     *
     * @return
     */
    @PostMapping("/list")
    public ResponseResult<IPage<SysRole>> queryPageList(@RequestBody RoleModel model) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        Page<SysRole> page = new Page<SysRole>(model.getPageNo(), model.getPageSize());
        if (StringUtils.isNotEmpty(model.getRoleName())) {
            queryWrapper.lambda().eq(SysRole::getRoleName, model.getRoleName());
        }
        queryWrapper.lambda().orderBy(StringUtils.isNotEmpty(model.getOrder()), model.getOrder().toUpperCase().indexOf("ASC") >= 0, SysRole::getCreateTime);
        IPage<SysRole> pageList = sysRoleService.page(page, queryWrapper);
        return ResponseResult.Success(pageList);
    }

    /**
     * 用户角色授权功能，查询菜单权限树
     *
     * @param
     * @return
     */
    @GetMapping("/queryTreeList")
    public ResponseResult<Map<String, Object>> queryTreeList() {
        //全部权限ids
        List<String> ids = Lists.newArrayList();
        LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
        query.eq(SysPermission::getDelFlag, CommonConstants.DEL_FLAG_0);
        query.orderByAsc(SysPermission::getSortNo);
        List<SysPermission> list = permissionService.list(query);
        for (SysPermission sysPer : list) {
            ids.add(sysPer.getId());
        }
        List<TreeModel> treeList = new ArrayList<>();
        getTreeModelList(treeList, list, null);
        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put("treeList", treeList); //全部树节点数据
        resMap.put("ids", ids);//全部树ids
        return ResponseResult.Success(resMap);
    }

    /**
     * 查询数据规则数据
     */
//    @GetMapping(value = "/datarule/{permissionId}/{roleId}")
//    public Result<?> loadDatarule(@PathVariable("permissionId") String permissionId,@PathVariable("roleId") String roleId) {
//        List<SysPermissionDataRule> list = sysPermissionDataRuleService.getPermRuleListByPermId(permissionId);
//        if(list==null || list.size()==0) {
//            return Result.error("未找到权限配置信息");
//        }else {
//            Map<String,Object> map = new HashMap<>();
//            map.put("datarule", list);
//            LambdaQueryWrapper<SysRolePermission> query = new LambdaQueryWrapper<SysRolePermission>()
//                    .eq(SysRolePermission::getPermissionId, permissionId)
//                    .isNotNull(SysRolePermission::getDataRuleIds)
//                    .eq(SysRolePermission::getRoleId,roleId);
//            SysRolePermission sysRolePermission = sysRolePermissionService.getOne(query);
//            if(sysRolePermission==null) {
//                //return Result.error("未找到角色菜单配置信息");
//            }else {
//                String drChecked = sysRolePermission.getDataRuleIds();
//                if(oConvertUtils.isNotEmpty(drChecked)) {
//                    map.put("drChecked", drChecked.endsWith(",")?drChecked.substring(0, drChecked.length()-1):drChecked);
//                }
//            }
//            return Result.ok(map);
//            //TODO 以后按钮权限的查询也走这个请求 无非在map中多加两个key
//        }
//    }
    private void getTreeModelList(List<TreeModel> treeList, List<SysPermission> metaList, TreeModel temp) {
        for (SysPermission permission : metaList) {
            String tempPid = permission.getParentId();
            TreeModel tree = new TreeModel(permission.getId(), tempPid, permission.getName(), permission.getRuleFlag(), permission.isLeaf());
            if (temp == null && StringUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getKey())) {
                temp.getChildren().add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }

        }
    }


}
